package com.bianguo.android.bprinter.aspects;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;

import com.bianguo.android.bprinter.annotations.PermissionCheck;
import com.bianguo.android.baselibrary.utils.PermissionHelper;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Aspect
public class PermissionCheckAspect {

    @Pointcut("execution(@com.bianguo.android.bprinter.annotations.PermissionCheck * *(..))")
    public void methodPoint() {}

    @Around("methodPoint()")
    public Object joinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        PermissionCheck annotation = method.getAnnotation(PermissionCheck.class);
        String[] permissions = annotation.permissions();
        int requestCode = annotation.requestCode();
        Object aThis = joinPoint.getThis();
        boolean permission = false;
        if (aThis instanceof Activity) {
            permission = PermissionHelper.getInstance((Context) aThis).isPermission(aThis, permissions, requestCode);
        } else if (aThis instanceof Fragment){
            Fragment fragment = (Fragment) aThis;
            permission = PermissionHelper.getInstance(fragment.getActivity()).isPermission(fragment, permissions, requestCode);
        }
        if (permission) {
            Object result = joinPoint.proceed();
            return result;
        }
        return null;
    }
}
